package com.xdf.docmanagementsystem.service.impl;

import com.xdf.docmanagementsystem.dao.DocDepartmentMapper;
import com.xdf.docmanagementsystem.dao.DocumentMapper;
import com.xdf.docmanagementsystem.entity.DocDepartment;
import com.xdf.docmanagementsystem.entity.Document;
import com.xdf.docmanagementsystem.service.ValidateService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @program: doc-management-system
 * @description:文档类别验证
 * @author: Zhang
 * @create: 2020-06-30 10:24
 **/
@Service
public class DocDepartmentValidateServiceImpl implements ValidateService<DocDepartment> {
    private DocDepartmentMapper docDepartmentMapper;
    private DocumentMapper documentMapper;

    @Autowired
    public DocDepartmentValidateServiceImpl(DocDepartmentMapper docDepartmentMapper, DocumentMapper documentMapper) {
        this.docDepartmentMapper = docDepartmentMapper;
        this.documentMapper = documentMapper;
    }

    @Override
    public boolean shouldInsert(DocDepartment item) throws Exception {
        if (item == null || StringUtils.isEmpty(item.getDocCategory())) return false;
        List<DocDepartment> list = docDepartmentMapper.selectByParam(DocDepartment.builder().docCategory(item.getDocCategory()).categoryStatus(1).build());
        return list == null || list.size() <= 0;
    }

    @Override
    public boolean shouldUpdate(DocDepartment item) throws Exception {
        if (item == null || item.getId() == null) {
            return false;
        }
        List<DocDepartment> list = docDepartmentMapper.selectByParam(DocDepartment.builder().docCategory(item.getDocCategory()).categoryStatus(1).build());
        if (CollectionUtils.isEmpty(list)) return true;
        if (list.size() == 1) {
            DocDepartment docDepartment = list.get(0);
            return Objects.equals(docDepartment.getId(), item.getId());
        }
        return false;
    }

    @Override
    public boolean shouldDelete(DocDepartment item) throws Exception {
        if (item == null || item.getId() == null) {
            return false;
        }
        List<DocDepartment> children = docDepartmentMapper.selectByParam(DocDepartment.builder().parentId(item.getId()).categoryStatus(1).build());
        List<Document> documents = documentMapper.selectByParam(Document.builder().docStatus(1).docDeptId(item.getId()).build());
        return CollectionUtils.isEmpty(children) && CollectionUtils.isEmpty(documents);
    }
}
